package com.emm.yixun.mobile.uptools;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import android.util.Log;

import com.emm.yixun.mobile.application.EmmApplication;

public class UpDateInfo {
	public String onFileItemClick(String filename) {
		String uploadUrl = "http://192.168.1.123/my_upload/UploadServlet";
		String end = "\r\n";
		String twoHyphens = "--"; // 两个连字符
		String boundary = "******"; // 分界符的字符串
		String result = "";
		try {
			URL url = new URL(uploadUrl);
			HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
			httpURLConnection.setDoInput(true);
			httpURLConnection.setDoOutput(true);
			httpURLConnection.setUseCaches(false);
			httpURLConnection.setRequestMethod("POST");
			// 设置Http请求头
			httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
			httpURLConnection.setRequestProperty("Charset", "UTF-8");
			// 必须在Content-Type 请求头中指定分界符中的任意字符串
			httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

			// 定义数据写入流，准备上传文件
			DataOutputStream dos = new DataOutputStream(httpURLConnection.getOutputStream());
			dos.writeBytes(twoHyphens + boundary + end);
			// 设置与上传文件相关的信息
			dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\""
					+ filename.substring(filename.lastIndexOf("/") + 1) + "\"" + end);
			dos.writeBytes(end);

			FileInputStream fis = new FileInputStream(filename);
			byte[] buffer = new byte[8192]; // 8k
			int count = 0;
			// 读取文件夹内容，并写入OutputStream对象
			while ((count = fis.read(buffer)) != -1) {
				dos.write(buffer, 0, count);
			}
			fis.close();
			dos.writeBytes(end);
			dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
			dos.flush();
			// 开始读取从服务器传过来的信息
			InputStream is = httpURLConnection.getInputStream();
			InputStreamReader isr = new InputStreamReader(is, "utf-8");
			BufferedReader br = new BufferedReader(isr);
			result = br.readLine();
			EmmApplication.T("上传返回参数：" + result);
			dos.close();
			is.close();
		} catch (Exception e) {
			Log.w("上传错误", e.getMessage());
		}
		return result;
	}

}